package com.gewu.pm.ui.dialog;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppAdapter;
import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * 选择经办人对话框
 */
public final class SelectHandlingPersonDialog {

    public static final class Builder
            extends BaseDialog.Builder<Builder>
            implements BaseAdapter.OnItemClickListener {

        private OnListener mListener;

        private final TextView mCancelView;
        private final TextView mTitleView;
        private final TextView mConfirmView;
        private final EditText mSearchEdit;
        private final RecyclerView mRecyclerView;
        private final HandlingPersonAdapter mAdapter;

        /** 所有经办人列表 */
        private final List<HandlingPersonBean> mAllPersonList = new ArrayList<>();
        /** 当前选中的经办人（单选模式） */
        private String mSelectedPerson = null;
        /** 是否多选模式 */
        private boolean mMultiSelect = false;

        public Builder(Context context) {
            super(context);
            setContentView(R.layout.select_handling_person_dialog);
            setWidth(WindowManager.LayoutParams.MATCH_PARENT);
            // 设置高度为屏幕的 2/3
            setHeight(getResources().getDisplayMetrics().heightPixels * 2 / 3);

            mCancelView = findViewById(R.id.tv_handling_person_cancel);
            mTitleView = findViewById(R.id.tv_handling_person_title);
            mConfirmView = findViewById(R.id.tv_handling_person_confirm);
            mSearchEdit = findViewById(R.id.et_handling_person_search);
            mRecyclerView = findViewById(R.id.rv_handling_person_list);

            setOnClickListener(mCancelView, mConfirmView);

            // 初始化经办人数据
            initHandlingPersonData();

            // 设置适配器
            mAdapter = new HandlingPersonAdapter(getContext());
            mAdapter.setData(mAllPersonList);
            mAdapter.setOnItemClickListener(this);
            mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
            mRecyclerView.setAdapter(mAdapter);
            
            // 添加分割线
            DividerItemDecoration divider = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
            divider.setDrawable(getContext().getDrawable(R.drawable.divider_horizontal_with_margin));
            mRecyclerView.addItemDecoration(divider);

            // 设置搜索功能
            setupSearch();
        }

        /**
         * 初始化经办人数据
         */
        private void initHandlingPersonData() {
            mAllPersonList.add(new HandlingPersonBean("张三", "A292877"));
            mAllPersonList.add(new HandlingPersonBean("李四", "A292878"));
            mAllPersonList.add(new HandlingPersonBean("王五", "A292879"));
            mAllPersonList.add(new HandlingPersonBean("赵六", "A292880"));
            mAllPersonList.add(new HandlingPersonBean("钱七", "A292881"));
            mAllPersonList.add(new HandlingPersonBean("孙八", "A292882"));
            mAllPersonList.add(new HandlingPersonBean("周九", "A292883"));
            mAllPersonList.add(new HandlingPersonBean("吴十", "A292884"));
        }

        /**
         * 设置搜索功能
         */
        private void setupSearch() {
            mSearchEdit.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    String keyword = s.toString().trim();
                    filterPersonList(keyword);
                }
            });
        }

        /**
         * 过滤经办人列表
         */
        private void filterPersonList(String keyword) {
            if (TextUtils.isEmpty(keyword)) {
                // 显示所有经办人
                mAdapter.setData(mAllPersonList);
            } else {
                // 根据关键字过滤（名称或编码）
                List<HandlingPersonBean> filteredList = new ArrayList<>();
                for (HandlingPersonBean person : mAllPersonList) {
                    if (person.getName().contains(keyword) || person.getCode().contains(keyword)) {
                        filteredList.add(person);
                    }
                }
                mAdapter.setData(filteredList);
            }
        }

        /**
         * 设置默认选中的经办人（单选模式）
         */
        public Builder setDefaultPerson(String personName) {
            mSelectedPerson = personName;
            if (mAdapter != null) {
                for (int i = 0; i < mAllPersonList.size(); i++) {
                    HandlingPersonBean bean = mAllPersonList.get(i);
                    bean.setSelected(bean.getName().equals(personName));
                }
                mAdapter.notifyDataSetChanged();
            }
            return this;
        }
        
        /**
         * 设置默认选中的经办人（多选模式）
         */
        public Builder setDefaultPersons(String persons) {
            if (mAdapter != null && !TextUtils.isEmpty(persons)) {
                String[] personArray = persons.split("、");
                for (int i = 0; i < mAllPersonList.size(); i++) {
                    HandlingPersonBean bean = mAllPersonList.get(i);
                    for (String person : personArray) {
                        if (bean.getName().equals(person.trim())) {
                            bean.setSelected(true);
                            break;
                        }
                    }
                }
                mAdapter.notifyDataSetChanged();
            }
            return this;
        }
        
        /**
         * 设置是否多选模式
         */
        public Builder setMultiSelect(boolean multiSelect) {
            mMultiSelect = multiSelect;
            return this;
        }

        /**
         * 设置监听器
         */
        public Builder setListener(OnListener listener) {
            mListener = listener;
            return this;
        }

        @SingleClick
        @Override
        public void onClick(View view) {
            int viewId = view.getId();
            if (viewId == R.id.tv_handling_person_cancel) {
                // 取消
                dismiss();
                if (mListener != null) {
                    mListener.onCancel(getDialog());
                }
            } else if (viewId == R.id.tv_handling_person_confirm) {
                // 确定
                if (mMultiSelect) {
                    // 多选模式：收集所有选中的项
                    List<String> selectedPersons = new ArrayList<>();
                    for (HandlingPersonBean bean : mAllPersonList) {
                        if (bean.isSelected()) {
                            selectedPersons.add(bean.getName());
                        }
                    }
                    if (selectedPersons.isEmpty()) {
                        // 如果没有选择，直接返回，不关闭弹窗
                        return;
                    }
                    dismiss();
                    if (mListener != null) {
                        String result = TextUtils.join("、", selectedPersons);
                        mListener.onSelected(getDialog(), result);
                    }
                } else {
                    // 单选模式
                    if (TextUtils.isEmpty(mSelectedPerson)) {
                        // 如果没有选择，直接返回，不关闭弹窗
                        return;
                    }
                    dismiss();
                    if (mListener != null) {
                        mListener.onSelected(getDialog(), mSelectedPerson);
                    }
                }
            }
        }

        /**
         * {@link BaseAdapter.OnItemClickListener}
         */
        @Override
        public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
            HandlingPersonBean selectedBean = mAdapter.getItem(position);
            
            if (mMultiSelect) {
                // 多选模式：切换选中状态
                selectedBean.setSelected(!selectedBean.isSelected());
                mAdapter.notifyItemChanged(position);
            } else {
                // 单选模式：取消之前选中的项
                for (HandlingPersonBean bean : mAdapter.getData()) {
                    bean.setSelected(false);
                }
                
                // 设置当前选中的项
                selectedBean.setSelected(true);
                mSelectedPerson = selectedBean.getName();
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    /**
     * 经办人适配器
     */
    private static final class HandlingPersonAdapter extends AppAdapter<HandlingPersonBean> {

        private HandlingPersonAdapter(Context context) {
            super(context);
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new ViewHolder();
        }

        private final class ViewHolder extends AppAdapter<?>.ViewHolder {

            private final CheckBox mCheckBox;
            private final ImageView mAvatarView;
            private final TextView mNameView;
            private final TextView mCodeView;

            private ViewHolder() {
                super(R.layout.select_handling_person_item);
                mCheckBox = findViewById(R.id.cb_handling_person);
                mAvatarView = findViewById(R.id.iv_handling_person_avatar);
                mNameView = findViewById(R.id.tv_handling_person_name);
                mCodeView = findViewById(R.id.tv_handling_person_code);
            }

            @Override
            public void onBindView(int position) {
                HandlingPersonBean bean = getItem(position);
                mCheckBox.setChecked(bean.isSelected());
                mNameView.setText(bean.getName());
                mCodeView.setText("车辆编码:" + bean.getCode());
                // 这里可以加载头像，暂时使用默认占位图
                mAvatarView.setImageResource(R.mipmap.logo_big_icon);
            }
        }
    }

    /**
     * 经办人数据Bean
     */
    private static class HandlingPersonBean {
        private String name;
        private String code;
        private boolean selected;

        public HandlingPersonBean(String name, String code) {
            this.name = name;
            this.code = code;
            this.selected = false;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public boolean isSelected() {
            return selected;
        }

        public void setSelected(boolean selected) {
            this.selected = selected;
        }
    }

    /**
     * 选择监听器
     */
    public interface OnListener {

        /**
         * 选择经办人
         *
         * @param dialog 对话框对象
         * @param personName 选中的经办人姓名
         */
        void onSelected(BaseDialog dialog, String personName);

        /**
         * 取消选择
         */
        default void onCancel(BaseDialog dialog) {}
    }
}

